import timeFormat from 'uview-ui/libs/function/timeFormat.js'

export function formatNumber(n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime(date,num) {
	console.info('utils/index.js',timeFormat(date,'yyyy-mm-dd'));
  // const year = date.getFullYear()
  // const month = date.getMonth() + 1
  // const day = date.getDate()

  // const hour = date.getHours()
  // const minute = date.getMinutes()
  // const second = date.getSeconds()

  // const t1 = [year, month, day].map(formatNumber).join('-')
  // const t2 = [hour, minute, second].map(formatNumber).join(':')
	
  if(num){
	  return timeFormat(date,'yyyy-mm-dd');
	  // return `${t1}`
  }else{
	  return timeFormat(date,'yyyy-mm-dd hh:MM:ss');
	  // return `${t1} ${t2}`
  }
}


export function showToast(title) {
  uni.showToast({
    title: title,
    icon: 'none',
	duration:2000
  })
}

export function showModalLogout(title,content,showCancel) {
	uni.setStorageSync('haveShowModal',true);
	uni.showModal({
		title: title,
		content:content,
		showCancel:showCancel,
		success(res){
			if (res.confirm) {
				uni.reLaunch({
					url:'/pages/index/login'
				})
			}
		},
		fail(){
			
		}

	})
}

export function debounce(func, delay) {
  let timer
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this)
    }, delay)
  }
}

/**
 *
 * @param min 最小值
 * @param max 最大值
 * @returns {string} 带一位小数的随机数
 */
export function getRandomDecimal(min, max) {
  return (min + (max - min) * Math.random()).toFixed(1)
}

/**
 *
 * @param min 最小值
 * @param max 最大值
 * @returns {Number} 整数随机数
 */
export function getRandomNum(min, max) {
  return parseInt(min + (max - min) * Math.random())
}


//将位置转换为地址
export function reverseGeocoder(qqmapsdk, {latitude, longitude}) {
  return new Promise((resolve, reject) => {
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude,
      },
      success: (res) => resolve(res),
      fail: (res) => reject(res)
    })
  })
}


/**
 * @param num 传入一个数
 * @returns {boolean} 是小数返回true
 */
export function isDecimalNum(num) {
  return String(num).indexOf('.') !== -1
}

/**
 * @param num1,@param num2 相加的两个数
 * @returns {number} 无精度丢失
 */
export function accAdd(arg1, arg2) {
    var r1, r2, m;
    try {
        r1 = arg1.toString().split(".")[1].length
    } catch(e) {
        r1 = 0
    }
    try {
        r2 = arg2.toString().split(".")[1].length
    } catch(e) {
        r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}

/**
 * @param num1,@param num2 相减的两个数
 * @returns {number} 无精度丢失
 */
export function accSub(num1,num2){
	var r1,r2,m;
	try{
    	r1 = num1.toString().split('.')[1].length;
	}catch(e){
    	r1 = 0;
	}
	try{
    	r2=num2.toString().split(".")[1].length;
	}catch(e){
    	r2=0;
	}
	m=Math.pow(10,Math.max(r1,r2));
	var n=(r1>=r2)?r1:r2;
	return (Math.round(num1*m-num2*m)/m).toFixed(n);
}

/**
 * @param idnum 护照证件号码
 * @returns {boolean} 是否通过校验
 */
export function checkPassport(idnum) {
  if (!idnum) return false;
  idnum = idnum.trim();
  // var re = /(^[EeKkGgDdSsPpHh]\d{8}$)|(^(([Ee][a-fA-F])|([DdSsPp][Ee])|([Kk][Jj])|([Mm][Aa])|(1[45]))\d{7}$)/;
  var re = /^([a-zA-z]|[0-9]){5,17}$/;
  var card = idnum.toUpperCase();
  return re.test(card);
};

/**
 * @param idnum 港澳通行证证件号码
 * @returns {boolean} 是否通过校验
 */
export function checkHKandMcPass(idnum){
	if (!idnum) return false;
	idnum = idnum.trim();
	var re =  /^[CW]\d{8}$/;//大陆-港澳
	var re2 = /^[HM]\d{10}$/;//港澳—大陆
	var re3 = /^[HM]\d{8}$/;//港澳—大陆
	return re.test(idnum) || re2.test(idnum) || re3.test(idnum);	
}


/**
 * 检测 身份证 【uview提供的检测不包含真实性】
 * @param idnum 身份证号码
 * @returns {boolean} 是否通过校验
 */
export const checkIDCard = function (idnum) {
  if (!idnum) return false;

  idnum = idnum.trim();
  if (idnum.length == 15) return false;
  if (!(idnum.length == 18 && /\d{17}[\dxX]/.test(idnum))) return false;

  //身份证每位数字的权重
  var RATIO = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  //身份证末尾数字
  var REMAINDER = ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'];
  var idNumArr = idnum.split('');
  var lastValue = idNumArr[17].toLocaleLowerCase(); //最后一位数字或x
  var sum = 0;
  for (var i = 0; i < 17; i++) {
    sum += idNumArr[i] * RATIO[i];
  }
  return lastValue == REMAINDER[sum % 11];
};

// 香港身份证校验
export const isXgIDCard = function(str){
	var strValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	 // basic check length
	 if (str.length < 8)
	 return false;
	 // handling bracket
	 if (str.charAt(str.length-3) == '(' && str.charAt(str.length-1) == ')')
	 str = str.substring(0, str.length - 3) + str.charAt(str.length -2);
	 // convert to upper case
	 str = str.toUpperCase();
	 // regular expression to check pattern and split
	 var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/;
	 var matchArray = str.match(hkidPat);
	 // not match, return false
	 if (matchArray == null) return false;
	 return true;
	
}
// 澳门身份证校验

export const isAmIDCard = function(str){
	var checkIDCard = /^[1|5|7]\d{6}[(\d)]{3}$/;
// 			console.log(checkIDCard.test(str));
	return checkIDCard.test(str);
	
}
// 台湾身份证验证
export const isTwIDCard = function(idcard){
	var checkIDCard = /^[A-Z][1-2]\d{8}$/;
	if (checkIDCard.test(idcard)){
		var area={'A':10,'B':11,'C':12,'D':13,'E':14,'F':15,'G':16,'H':17,'J':18,'K':19,'L':20,'M':21,'N':22,'P':23,'Q':24,'R':25,'S':26,'T':27,'U':28,'V':29,'X':30,'Y':31,'W':32,'Z':33,'I':34,'O':35};
		var idcard_array = new Array();        
		idcard_array = idcard.split("");
		
		var jym=parseInt(area[idcard_array[0]]/10)+9*(area[idcard_array[0]]%10)+8*idcard_array[1]+7*idcard_array[2]+6*idcard_array[3]+5*idcard_array[4]+4*idcard_array[5]+3*idcard_array[6]+2*idcard_array[7]+1*idcard_array[8];
		
		jym=(10-jym%10)%10;
		
		if(idcard_array[9]==jym)
		{       
			return true;
		}else{
			return false;
		}
	}else{
		return false;
	}
}

// 台胞证验证
export const checkTaiBao = function(idnum){
	idnum = idnum.trim();
	var re = /^\d{8}|^\d{18}|^[a-zA-Z0-9]{10}$/;
	return re.test(idnum);
}

// 回乡证(港澳居民来往内地)
export const HKandMacaoResiden = function(idnum){
	if (!idnum) return false;
	idnum = idnum.trim();
	var re = /^[HM]\d{10}$/;
	var re2 = /^[HM]\d{8}$/;
	return re.test(idnum) || re2.test(idnum);
}

// 外国人居留证
export const foreignPermanentResiden = function(idnum){
	idnum = idnum.trim();
	var re = /^[a-zA-Z]{3}[0-9]{12}$/;
	return re.test(idnum);
}